using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Microsoft.Build.Evaluation;

namespace projectfile
{
    public class ProjectParser
    {
        public void GetEbcXmlFilenames(Project project) {
            Trace.TraceInformation("Searching for *.ebc.xml files");
            EbcXmlFilenames(GetFilenames(project));
        }

        public event Action<IEnumerable<string>> EbcXmlFilenames;

        private static IEnumerable<string> GetFilenames(Project project) {
            foreach (var item in project.Items) {
                if ((item.ItemType == "Content") && (item.EvaluatedInclude.EndsWith(".ebc.xml"))) {
                    var filename = Path.Combine(project.DirectoryPath, item.EvaluatedInclude);
                    Trace.TraceInformation("  Found file {0}", filename);
                    yield return filename;
                }
            }
        }

        public void GetGeneratedEbcCsFilename(Project project) {
            Trace.TraceInformation("Searching for generated.ebc.cs");
            var filename = GetFilename(project);
            Trace.TraceInformation("  Found file {0}", filename);
            GeneratedEbcCsFilename(filename);
        }

        public event Action<string> GeneratedEbcCsFilename;

        private static string GetFilename(Project project) {
            const string filename = "generated.ebc.cs";
            foreach (var item in project.Items) {
                if ((item.ItemType == "Compile") && (item.EvaluatedInclude.EndsWith(filename))) {
                    return Path.Combine(project.DirectoryPath, item.EvaluatedInclude);
                }
            }
            return Path.Combine(project.DirectoryPath, filename);
        }
    }
}